<template>
  <div class="perceptionComment" style="height: 200px;">
    <div>评论<span style="font-weight: 600;margin-left: 5px">{{count}}</span></div>
    <div class="clickheader" @click="xpl()">
      <div style="margin:5px 10px 0 0"><el-avatar :src="usreimg?usreimg:imgsrc" :size="30" /></div>
      <div class="clickinput">写下你的评论...</div>
    </div>

    <div style="padding: 10px 0px" class="commentItem" v-for="(v,i) in allpl.slice(0,2)">
      <div style="margin-right: 5px;margin-bottom:5px;line-height: 30px;display: flex;justify-content: start" class="header">
        <el-avatar :src="v.touxiangsrc?v.touxiangsrc:imgsrc" :size="30" />
        <div style="margin-left: 10px;">
          {{ v.name }}
        </div>
      </div>
      <div style="margin-left: 40px;word-wrap:break-word">
        {{ v.body }}
        <div style="display: flex;justify-content: space-between;margin-top: 10px">
          <div style="color: #b5b5b5;font-size: 10px">{{ v.time }}</div>
          <div><i class="el-icon-chat-round" style="padding-right: 10px" @click="addplhf(v)"></i><van-icon :name="v.ismy==1?'good-job':'good-job-o'" :color="v.ismy==1?'#ff0000':''" style="padding-right: 2px" @click="adddz(v)" />
            {{ v.dz }}</div>
        </div>
      </div>
    </div>

    <div @click="drawer = true" v-if="allpl.length>2" style="color:#b5b5b5;text-align: center;font-size: 10px;padding: 15px 0">
      查看全部评论 >
    </div>

    <el-drawer
        title="全部评论"
        direction="btt"
        :visible.sync="drawer"
        size="100%">
      <!--   如果没有评论显示空内容   -->
      <el-empty description="还没有评论，发表第一个评论吧" v-if="allpl.length==0">
        <van-button plain color="#5a8dffe8" size="small" @click="drawerpl=true">写评论</van-button>
      </el-empty>

      <main v-infinite-scroll="load" infinite-scroll-disabled="nomore">
        <!--     一级评论     -->
        <div style="padding: 10px 15px 0" class="commentItem" v-for="(v,i) in allpl">
          <div style="margin-right: 5px;margin-bottom:5px;line-height: 30px;display: flex;justify-content: start" class="header">
            <el-avatar :src="v.touxiangsrc?v.touxiangsrc:imgsrc" :size="30" />
            <div style="margin-left: 10px;">
              {{ v.name }}
            </div>
          </div>
          <div style="margin-left: 40px;word-wrap:break-word">
            {{ v.body }}
            <div style="display: flex;justify-content: space-between;margin-top: 10px">
              <div style="color: #b5b5b5;font-size: 10px">{{ v.time }}</div>
              <div><i class="el-icon-chat-round" style="padding-right: 10px" @click="addplhf(v,i)"></i><van-icon :name="v.ismy==1?'good-job':'good-job-o'" @click="adddz(v)" :color="v.ismy==1?'#ff0000':''" style="padding-right: 2px" />
                {{ v.dz }}</div>
            </div>

            <el-collapse-transition>
              <el-main v-if="v.fold" style="padding: 0;">
              <div style="padding: 0px 0px 0px" class="commentItem" v-for="hf in v.comments" :key="hf.pl_id">

                <div style="margin-right: 5px;margin-bottom:5px;line-height: 30px;display: flex;justify-content: start" class="header">
                  <el-avatar :src="hf.touxiangsrc?hf.touxiangsrc:imgsrc" :size="30" />
                  <div style="margin-left: 10px;" v-if="hf.root_id==hf.hf_id">
                    {{ hf.name }}
                  </div>
                  <div style="margin-left: 10px;display: flex;align-items: center" v-else>
                    {{ hf.hf_user }} <div style="border: transparent solid 4px;width: 0;height: 0;border-left: #b5b5b5 solid 4px;margin: 0 2px 0 5px"></div>{{ hf.name }}
                  </div>
                </div>
                <div style="margin-left: 40px;word-wrap:break-word">
                  {{ hf.body }}
                  <div style="display: flex;justify-content: space-between;margin-top: 10px">
                    <div style="color: #b5b5b5;font-size: 10px">{{ hf.time }}</div>
                    <div><i class="el-icon-chat-round" style="padding-right: 10px" @click="addplhf(hf,i)"></i><van-icon :name="hf.ismy==1?'good-job':'good-job-o'" :color="hf.ismy==1?'#ff0000':''" @click="adddz(hf)" style="padding-right: 2px" />
                      {{ hf.dz }}</div>
                  </div>
                </div>
              </div>
            </el-main>
            </el-collapse-transition>

            <div class="lottie_loading" v-if="v.twocommentloading==1" >
              <el-main style="height: 60px" v-loading="true"></el-main>
            </div>

            <div v-if="v.hflength>0" style="width: 100%;height: 20px;display: flex;align-items: center">
              <span style="width: 30px;height: 1px;background: #bebebe;"></span>
              <span class="comment_next" @click="addtowComment(v,i)" v-if="(v.fold && v.hflength!=v.comments.length) || !v.fold">{{!v.fold?`展开${v.hflength}条回复`:'展开更多回复'}}</span>
              <span class="comment_up" v-if="v.fold" @click="deltowComment(v,i)">收起</span>
            </div>
          </div>
        </div>
      </main>


      <div style="position: fixed;background-color: white;bottom: 0;left: 0;width: 100%;display: flex;justify-content: space-between;align-items: center;border-top: 1px solid rgba(224,224,224,0.6);padding: 0px 10px;z-index: 10000;
            color: #b5b5b5" @click="drawerplchange()">
        评论千万条，友善第一条
        <el-button type="text">发布</el-button>
      </div>
      <el-collapse-transition>
        <el-drawer
            class="perceptionComment_drawer"
            title="发布评论"
            direction="btt"
            :visible.sync="drawerpl"
            :append-to-body="true"
            :with-header="false">
          <div style="padding: 10px;">
            <el-input
                type="textarea"
                autosize
                :placeholder="pltip"
                resize="none"
                maxlength="200"
                show-word-limit
                autofocus
                v-model="pl">
            </el-input>
            <el-button type="text" style="float: right;padding-right: 10px" @click="fabu" v-if="!huifuflag">发布</el-button>
            <el-button type="text" style="float: right;padding-right: 10px" @click="huifu" v-else>回复</el-button>
          </div>
        </el-drawer>
      </el-collapse-transition>
    </el-drawer>
  </div>
</template>

<script>
import defaultuserimg from "@/assets/userAvatar.png";
import {mapState} from 'vuex'
import qs from "qs";
import {
  addCommentArticle,
  addCommentHFArticle, delLoveComment,
  getCommentArticle,
  getTwoCommentArticle,
  loveComment
} from "../utils/api";
import {perceptiontime} from "../utils/time";
export default {
  name: "PerceptionComment",
  data(){
    return {
      imgsrc:defaultuserimg,
      drawer:false,
      drawerpl:false,
      pl:'',
      allpl:'',
      nomore:false,
      shoucipl:[],
      huifupl:[],
      hechengpl:[
        ],
      pltip:'评论千万条，友善第一条',
      huifu_id:'',
      huifuflag:false,
      loveCommentHistory:[], //操作过点赞的评论
    }
  },
  props:{
    pid:String,
    count:Number
  },
  computed:{
    ...mapState([
      'usreimg','username',"usermingzi",'userid'
    ])
  },
  methods:{
    load(){
      getCommentArticle({p_id:this.pid,begin:this.allpl.length,step:20}).then(respose => {
        if (respose.status === 200) {
          let arr = respose?.body;
          if(arr){
            if(arr.length<20){
              this.nomore=true
            }
          }
          //处理所有评论 分类
          arr.forEach(v=>{
            //处理头像
            if(v.touxiangsrc){
              v.touxiangsrc=v.touxiangsrc.replace(/public/, 'http://cloud.pinggai8.com');
            }
            //处理时间
            v.time = perceptiontime(v.time)
            v.fold = false
            v.comments=[]
          })
          this.allpl = this.allpl.concat(arr)
        }
      })
    },
    fabu(){
      if(this.pl){
        /*判断该用户是否为当日首次发布*/
        let day = 0
        let localStorageValue = localStorage.getItem('dailyComments')
        if(!localStorageValue){
          day = 1
        }else{
          if(new Date().getDate()!=new Date(localStorageValue-0).getDate()){
            day = 1
          }else{
            /*同一天 进一步判断是否为当天*/
            let _time = new Date()
            if(!(localStorageValue-0>=new Date(_time.setDate(_time.getDate())).setHours(0,0,0,0) && localStorageValue-0<new Date(_time.setDate(_time.getDate()+1)).setHours(0,0,0,0))){
              day = 1
            }
          }
        }

        addCommentArticle(qs.stringify({p_id:this.pid,body:this.pl,day})).then(respose=>{
          if(respose.status===200){
            /*dailyActivities('dailyComments',3,0)*/
            this.allpl.unshift({
              body:this.pl,
              name:this.usermingzi,
              touxiangsrc:this.usreimg,
              time:"1 分钟前",
              dz:0,
              comments:[],
              fold:false,
              hf_id:null,
              hflength:0,
              p_id:this.pid,
              pl_id:respose?.body,
              root_id:null,
              u_id:this.userid
            })
            this.drawerpl=false;
            if(respose.wxdaily){
              if(respose.wxdaily!=0){
                this.$notify({
                  title: '发布成功',
                  message: `获得奖励￥${respose.wxdaily}元`,
                  type: 'success'
                });
              }
              localStorage.setItem('dailyComments',new Date().getTime()+'')
            }else{
              this.$message.success("发布成功");
            }
            this.$emit('addcount')
            this.pl='';
          }
        })
      }else{
        this.$message.warning("你还没有输入评论的内容呢")
      }
    },
    xpl(){
      this.pltip='评论千万条，友善第一条'
      this.drawer=true;
      setTimeout(()=>{
        this.drawerpl=true;
      },300)
    },
    drawerplchange(){
      this.pltip='评论千万条，友善第一条'
      this.drawerpl=true;
    },
    addplhf(v,i){
      this.pltip='回复 '+v.name;
      this.huifu_id={
        value:v,
        index:i
      };
      if(this.drawer){
        this.drawerpl=true;
      }else{
        this.drawer=true;
        setTimeout(()=>{
          this.drawerpl=true;
        },300)
      }
      this.huifuflag=true
    },
    adddz(v){
      console.log(v,v.pl_id)
      if(!this.loveCommentHistory.some(e=>e.pl_id==v.pl_id)){
        v.oldismy = v.ismy
        this.loveCommentHistory.push(v)
      }
      if(v.ismy==1){
        v.dz--
        v.ismy = 0
      }else{
        v.dz++
        v.ismy = 1
      }
    },
    huifu(){
      if(this.huifu_id && this.pl){
        /*判断该用户是否为当日首次发布*/
        let day = 0
        let localStorageValue = localStorage.getItem('dailyComments')
        if(!localStorageValue){
          day = 1
        }else{
          if(new Date().getDate()!=new Date(localStorageValue-0).getDate()){
            day = 1
          }else{
            /*同一天 进一步判断是否为当天*/
            let _time = new Date()
            if(!(localStorageValue-0>=new Date(_time.setDate(_time.getDate())).setHours(0,0,0,0) && localStorageValue-0<new Date(_time.setDate(_time.getDate()+1)).setHours(0,0,0,0))){
              day = 1
            }
          }
        }
        addCommentHFArticle(qs.stringify({p_id:this.pid,body:this.pl,hf_id:this.huifu_id.value.pl_id,root_id:this.huifu_id.value.root_id || this.huifu_id.value.pl_id,day})).then(respose=>{
          if(respose.status===200){

            this.allpl[this.huifu_id.index].comments.unshift({
              body:this.pl,
              dz:0,
              hf_id:this.huifu_id.value.pl_id,
              hf_user:this.huifu_id.value.name,
              p_id:this.huifu_id.value.p_id,
              root_id:this.huifu_id.value.root_id || this.huifu_id.value.pl_id,
              time:"1 分钟前",
              u_id:this.userid,
              touxiangsrc:this.usreimg,
              name:this.usermingzi,
              pl_id:respose.body
            })
            this.allpl[this.huifu_id.index].hflength++
            this.allpl[this.huifu_id.index].fold = true
            this.allpl.splice(this.huifu_id.index,1,this.allpl[this.huifu_id.index])

            this.drawerpl=false;
            if(respose.wxdaily){
              if(respose.wxdaily!=0){
                this.$notify({
                  title: '回复成功',
                  message: `获得奖励￥${respose.wxdaily}元`,
                  type: 'success'
                });
              }
              localStorage.setItem('dailyComments',new Date().getTime()+'')
            }else{
              this.$message.success("回复成功");
            }
            this.pl=''
            this.huifu_id = null
            this.huifuflag = false
          }
        })
      }else{
        this.$message.error("回复失败，请刷新尝试")
      }
    },
    addtowComment(v,i){
      v.twocommentloading = 1
      this.allpl.splice(i,1,v)
      getTwoCommentArticle({pl_id:v.pl_id,begin:v.comments.length,step:5}).then(res=>{
        if(res.status==200){
          let arr = res.body
          arr.forEach(v=>{
            //处理头像
            if(v.touxiangsrc){
              v.touxiangsrc=v.touxiangsrc.replace(/public/, 'http://cloud.pinggai8.com');
            }
            //处理时间
            v.time = perceptiontime(v.time)
          })
          setTimeout(()=>{
            v.comments.push(...arr)
            v.fold = true
            v.twocommentloading = 0
            this.allpl.splice(i,1,v)
          },300)
          /*this.$set(this.allpl[i],'comments',arr)*/
          /*
          this.$forceUpdate()*/
        }
      }).catch(err=>{
        console.log(err)
      })
    },
    deltowComment(v,i){
      v.fold = false
      this.allpl.splice(i,1,v)
    }
  },
  created() {
    getCommentArticle({p_id:this.pid,begin:this.allpl.length,step:3}).then(respose => {
      if (respose.status === 200) {
        this.allpl = respose?.body;
        //处理所有评论 分类
        this.allpl.forEach(v=>{
          //处理头像
          if(v.touxiangsrc){
            v.touxiangsrc=v.touxiangsrc.replace(/public/, 'http://cloud.pinggai8.com');
          }
          //处理时间
          v.time = perceptiontime(v.time)
          v.fold = false
          v.comments=[]
          v.twocommentloading=0
          /*if(v.hf_id){
            //属于回复类型的评论
            this.huifupl.unshift(v)
          }else{
            this.shoucipl.push(v)
            this.hechengpl.push([v])
          }*/
        })
      }
      /*console.log('回复类型',this.huifupl)
      console.log('首次类型',this.shoucipl)
*/
      /*/!*合并处理*!/
      this.hechengpl.forEach((hcv)=>{
        console.log('hcv',hcv)
        let newarr=[];
        this.huifupl=this.huifupl.filter(hfv=>{
          console.log('hfv',hfv)
          if(hcv[0].pl_id===hfv.hf_id){
            /!*说明当前找到了用户回复评论的父级评论
            * 将回复评论压入当前数组中*!/
            newarr.push([hfv]);
          }else{
            return hfv;
          }
        })
        hcv.push(newarr);
      })

      /!*处理三级回复*!/
      if(this.huifupl){
        this.hechengpl.forEach((hcv)=>{
          hcv[1].forEach(ejhf=>{
            let newarr = [];
            this.huifupl=this.huifupl.filter(hfv=>{
              if(ejhf[0].pl_id===hfv.hf_id){
                newarr.push([hfv])
              }else {
                return hfv;
              }
            })
            ejhf.push(newarr)
          })
        })
      }*/

      /*处理四级回复*/
      /*if(this.huifupl){
        this.hechengpl.forEach((hcv)=>{
          hcv[1].forEach(ejhf=>{
            ejhf[1].forEach(sjhf=>{
                sjhf.forEach(item=>{
                  let newarr = [];
                  this.huifupl=this.huifupl.filter(hfv=>{
                    if(item.pl_id===hfv.hf_id){
                      newarr.push(hfv)
                    }
                  })
                  sjhf.push(newarr)
                })
                /!*if(sjhf[0].pl_id===hfv.hf_id){
                  newarr.push(hfv)
                }else {
                  return hfv;
                }*!/
            })

           /!* ejhf.push(newarr)*!/
          })
        })
        console.log("说明有需要处理的四级回复")
      }*/

    })
  },
  beforeDestroy() {
    let add = []
    let del = []
    this.loveCommentHistory.map(e=>{
      if(e.oldismy<e.ismy){
        add.push(e.pl_id)
      }else if(e.oldismy>e.ismy){
        del.push(e.pl_id)
      }
    })

    if(add.length>0){
      loveComment(qs.stringify({
        plid:JSON.stringify(add)
      })).then().catch()
    }
    if(del.length>0){
      delLoveComment(qs.stringify({
        plid:JSON.stringify(del)
      })).then().catch()
    }
  }
}
</script>

<style scoped>
.clickheader{
  display: flex;
  justify-content: start;
  margin-top: 10px;
  align-items: center;
}
.clickinput{
  width: 100%;
  height: 35px;
  border: 1px solid rgba(189, 180, 180, 0.7);
  border-radius: 5px;
  padding: 0 10px;
  color: #b5b5b5;
  line-height: 35px;
}
.perceptionComment>>>.el-drawer__header{
  padding: 10px 20px 0;
  margin: 0 0 10px;
}
.perceptionComment>>>.el-drawer__body{
  padding-bottom: 50px;
}
.perceptionComment>>>.el-drawer__header span{
  text-align: center;
  color: black;
}
.perceptionComment>>>.van-button.van-button--default.van-button--normal{
  color: #0000FF!important;
}
.perceptionComment>>>.el-drawer.btt{
  border-radius:10px 10px 0 0;
}
.comment_next{
  font-size: 14px;
  color: #646464;
  padding: 0 12px 0 10px;
  background: url('../assets/commentnext.png') right 6px/10px 10px no-repeat;
}
.comment_up{
  font-size: 14px;
  color: #646464;
  padding: 0 12px 0 20px;
  background: url('../assets/commentup.png') right 6px/10px 10px no-repeat
}

.listhide-leave-active{
  animation: showHide 1s reverse linear;
}
.listhide-enter-active{
  animation: showHide 1s linear;
}
@keyframes showHide {
  0%{height: 0;}
  100%{height: auto;}
}
</style>
